package com.example.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pojo.PageData;
import com.example.pojo.ResultBean;
import com.example.pojo.Statute;
import com.example.service.IStatuteService;
import org.omg.PortableInterceptor.SUCCESSFUL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lyj
 * @since 2023-02-20
 */
@RestController
@RequestMapping("/statute")
public class StatuteController {

    @Autowired
    private IStatuteService statuteService;

    /**
     * 分页条件查询
     * @param pageData
     * @param map
     * @return
     */
    @GetMapping("/list")
    public ResultBean list(PageData pageData, @RequestParam Map<String, Object> map) {
        map.forEach((k, v) -> System.out.println(k + ":" + v));
        Page<Statute> page = new Page<>(pageData.getPageNum(), pageData.getPageSize());
        statuteService.lambdaQuery()
                .eq(!ObjectUtils.isEmpty(map.get("type")), Statute::getType, map.get("type"))
                .eq(!ObjectUtils.isEmpty(map.get("areaId")), Statute::getAreaId, map.get("areaId"))
                .and(!ObjectUtils.isEmpty(map.get("keyWord")),
                        qw -> qw.like(Statute::getTitle, map.get("keyWord")).or()
                                .like(Statute::getStemFrom, map.get("keyWord")))
                .page(page);
        return ResultBean.success(page);
    }

    /**
     * 新增或修改
     * @param statute
     * @return
     */
    @PostMapping("saveOrUpdate")
    public ResultBean saveOrUpdate(@RequestBody Statute statute){
        //若新增，则设置法律法规的发布时间
        if (statute.getId() == null) {
            statute.setPubDate(LocalDate.now());
        }
        boolean rs = statuteService.saveOrUpdate(statute);
        return rs ? ResultBean.success() : ResultBean.error();
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id")Long id){
        boolean b = statuteService.removeById(id);
        return b ? ResultBean.success() : ResultBean.error();
    }
}
